package cn.ihelloworld.controller;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.ihelloworld.bean.SysUser;

public class AdminLoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		String[] excludes={"/admin/login.html","/admin/login.do","/admin/logout.do"};
		String url=req.getRequestURI();
		for(String ex:excludes){
			if(url.contains(ex)){
				chain.doFilter(request, response);
				return;
			}
		}
		Logger.getLogger(getClass()).debug(url);
		Pattern pattern = Pattern.compile("/admin/[a-zA-Z,0-9,/]*\\w+[.](html|do)");
		Matcher matcher = pattern.matcher(url);
		boolean matched=matcher.find();
		HttpServletResponse res=(HttpServletResponse) response;
		if(url.endsWith("admin")||url.endsWith("admin/")){
			res.sendRedirect(req.getContextPath()+"/admin/login.html");
		}
		if(matched){
			if(req.getSession().getAttribute("admin")==null){
				Logger.getLogger(getClass()).debug("need administrator login!");
				res.sendRedirect(req.getContextPath()+"/admin/login.html");
			}else{
				SysUser user=(SysUser) req.getSession().getAttribute("admin");
				Logger.getLogger(getClass()).debug("login user is "+user.getAccount());
				chain.doFilter(request, response);
			}
			
		}else{
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
